<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 新闻文章
 *
 * @author www.dingwei.cn
 */
class AdmNewsModel extends MY_Model{
	
	private $tbNews = 'admin_news';
	private $tbNewsView = 'admin_news_view';
	
	/**
	 * 增加浏览次数
	 * @param unknown $consumerId
	 * @param unknown $newsId
	 * @return boolean
	 */
	public function newsView($consumerId,$newsId){
		
		$this->db->where('consumer_id',$consumerId);
		$this->db->where('news_id',$newsId);
		if ( ! $this->getOne($this->tbNewsView)){
			//不存在
			$data = array(
					'consumer_id'=>$consumerId,
					'news_id'=>$newsId,
					'time'=>date('Y-m-d'),
			);
			return $this->insert($this->tbNewsView, $data);
		}else{
			return false;
		}
	}
	
    /**
     * 获取列表数据
     * @return 	array
     * @author heyu
     */
    public function adminPcGetList(){
        $title = trim(get('title'));
        $type_ids = (int)get('type_ids');
        $keywords = trim(get('keywords'));
        $source = trim(get('source'));
        $top = (int)get('top');
        $status = (int)get('status');
        $send_date_from = strtotime(get('send_date_from'));
        $send_date_to = strtotime(get('send_date_to'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($title){
            $this->db->like(array('title' => $title));
        }

        if ($type_ids){
            $this->db->like(array('type_ids' => ','.$type_ids.','));
        }

        if ($keywords){
            $this->db->like(array('keywords' => $keywords));
        }

        if ($source){
            $this->db->like(array('source' => $source));
        }

        if ($top){
            $this->db->where(array('top' => $top));
        }

        if ($status){
            $this->db->where(array('status' => $status));
        }
        if($send_date_from){
            $this->db->where('addtime >=', $send_date_from);
        }
        if($send_date_to){
            $this->db->where('addtime <= ', strtotime('+1day', $send_date_to));
        }
        $this->db->order_by('top desc,sort asc');
        if($iSortCol_0 == 4){
            $this->db->order_by('read_number '.$sSortDir_0);
        }elseif ($iSortCol_0 == 7){
            $this->db->order_by('sort '.$sSortDir_0);
        }elseif ($iSortCol_0 == 8){
            $this->db->order_by('addtime '.$sSortDir_0);
        }else{
            $this->db->order_by(' addtime desc');
        }

        $this->db->select('id,imgs,type_ids,title,keywords,top,status,sort,source,addtime,read_number');

        $data = $this->pagination($this->tbNews);
        $typeIds = array();
        if(!empty($data['data'])) {
            foreach ($data['data'] as $k => $v) {
                $ids = explode(',', trim($v['type_ids'], ','));
                foreach ($ids as $iv) {
                    if (isset($iv) && !in_array($iv, $typeIds)) {
                        $typeIds[] = $iv;
                    }
                }
                $data['data'][$k]['type_ids'] = $ids;
            }
            get_instance()->loadModel('AdmNewsTypeModel', 'mNewsType', 'admin');
            $type = $this->mNewsType->getInfoByIds($typeIds);
            foreach ($data['data'] as $k => $v) {
                $typeNames = array();
                foreach ($v['type_ids'] as $kk => $vv) {
                    $typeNames[] = $type[$vv]['type_name'];
                }
                $data['data'][$k]['type_name'] = implode(',', $typeNames);
            }
        }
        return $data;
 	}

    /**
     * 获取新闻详情
     * @param $id
     * @param $mini     bool        true：少量数据
     * @return array
     * @author heyu
     */
 	public function getInfo($id, $mini = false){
        if (!$id){
            return array();
        }
        if ($mini){
            $this->db->select('id,title,read_number,keywords,top,status,sort,source')
                ->where(array('id' => $id));
            $tA = $this->getOne($this->tbNews);
            return $tA;
        }

        $this->db->select('id,imgs,type_ids,read_number,title,content,type,keywords,top,status,sort,source,addtime')
            ->where(array('id' => $id));
        $tA = $this->getOne($this->tbNews);
     
        if ($tA){
	        $imgArr = json_decode($tA['imgs'], true);

	        foreach ($imgArr as $k => $v){
	            $imgArr[$k] = getImage($v,'xs');
	        }
	        $tA['imgs'] = $imgArr;
	        $tA['addtime'] = dateFormat($tA['addtime'], true);
	        $tA['type_ids'] = explode(',', trim($tA['type_ids']));
        }
        return $tA;
    }

    /**
     * 获取新闻列表
     * @param integer $type_id 分类id
     * @param number $top	是否置顶
     * @param number $page	分页
     * @param number $ids	ids获取新闻[收藏使用]
     * @return array|array|string|array[]|number[]|unknown[]
     * @author zyl
     */
    public function appGetList($typeId = 0, $top = 0, $keyword = '', $page = 1, $ids = array()){
    	
    	if ($top){
    		$this->db->where('top',$top);
    	}
    	
    	if ($keyword){
    		$this->db->like('title',$keyword);
    	}
    	
    	if ($typeId){
	    	$this->db->like('type_ids',','.$typeId.',');
    	}
    	
    	if ($ids){
    		$this->db->where_in('id',$ids);
    	}
    	
    	$this->db->select('id,title,read_number,type,imgs,source');
    	$this->db->order_by('top desc,sort asc,addtime desc');
    	$tA = $this->appPage($this->tbNews, $page);
    	
    	foreach ($tA['list'] as $k=>$v){
    		
    		//头条，因为有2条轮播。所以，再特殊情况下处理
    		if ( ! $keyword && ! $ids){
	    		if ($page == 1 && $k < 3){
	    			//第一页前三条干掉
	    			unset($tA['list'][$k]);
	    			continue;
	    		}
    		}
    		
    		$imgs = json_decode($v['imgs'],true);
    		if ($imgs){
    			$tA['list'][$k]['imgs'] = array();
    			
    			if ($v['type'] == 1){
    				foreach ($imgs as $kk=>$vv){
    					$tA['list'][$k]['imgs_url'] = getImage($vv,'og');
    				}
    			}elseif ($v['type'] == 2){
    				foreach ($imgs as $kk=>$vv){
    					$tA['list'][$k]['imgs'][] = getImage($vv,'og');
    				}
    			}
    		}
    		
    		//数据
    		$tA['list'][$k]['read_number'] = empty($v['read_number'])? "0" : $v['read_number'];
    	}
    	
    	$tA['list'] = array_values($tA['list']);//重新排序
    	
    	return $tA['list'];
    }
    
    /**
     * 获取新闻列表
     * @param integer $type_id 分类id
     * @param number $top	是否置顶
     * @param number $page	分页
     * @param number $ids	ids获取新闻[收藏使用]
     * @return array|array|string|array[]|number[]|unknown[]
     * @author zyl
     */
    public function getTopList($typeId = 0){
    	
    	if ($typeId){
	    	$this->db->like('type_ids',','.$typeId.',');
    	}
    	
    	$this->db->select('id,title,read_number,type,imgs');
    	$this->db->order_by('top desc,sort asc,addtime desc');
    	$this->db->limit(3);
    	$tA = $this->getAll($this->tbNews);
    	
    	foreach ($tA as $k=>$v){
    		$imgs = json_decode($v['imgs'],true);
    		$tA[$k]['imgs_url'] = getImage($imgs[0],'og');
    		//数据
    		$tA[$k]['read_number'] = empty($v['read_number'])? "0" : $v['read_number'];
    		unset($tA[$k]['imgs']);
    	}
    	
    	return $tA;
    }
 	/**
 	 * 保存新闻
 	 * @param 	array 	$data
 	 * @param   integer $id
 	 * @return	boolean|integer
     * @author heyu
 	 */
 	public function save($data, $id = 0){
 		if($id){
 			$this->db->where('id', $id);
 			return $this->update($this->tbNews, $data);
 		}
 		
 		return $this->insert($this->tbNews, $data);
 	}

    /**
     * 删除
     * @param $id
     * @return bool
     * @author heyu
     */
 	public function deleteNews($id){
 	    if (!$id){
 	        return false;
        }
        $this->db->where(array('id' => $id));
 	    return $this->delete($this->tbNews);
    }

    /**
     * 查看分类下的新闻
     * @param $id       int         分类id
     * @return array
     * @author heyu
     */
    public function getNewsByNewsType($id){
        if (!$id){
            return array();
        }
        $this->db->select('id')
            ->where(array('type_ids' => ','.$id.','));
        $tA = $this->getAll($this->tbNews);
        return $tA;
    }
    
    /**
     * 获取置顶的广告
     * @param number $top 是否置顶  1-普通 2-置顶
     * @param number $limit 条数
     * @return array
     * @author zyl
     */
    public function getInfoByTop($top = 0,$limit = 0){
    	if ($top){
    		$this->db->where('top',$top);
    	}
    	$this->db->select('id,title')
    	->where('status',2)
    	->order_by('sort desc');
    	if ($limit){
    		$this->db->limit($limit);
    	}
    	$tA = $this->getAll($this->tbNews);
    	
    	return $tA;
    }
}